<?php
/**
 * Created by IntelliJ IDEA.
 * User: ty42
 * Date: 1/27/16
 * Time: 7:16 PM
 */

class Hospitalm extends CI_Model
{
    private $ela_prefix = 'http://elasticsearch.medical-lighter.com:19200/';
    private $ela_index = "hospital";
    
    const HOSPITAL_CODE_START = 100000;

    public static $sc = null;  // sphinx client instance


    function __construct()
    {
        parent::__construct();
    }
    
    public function transHospitalCode2id($hospital_code)
    {
        if ($hospital_code < self::HOSPITAL_CODE_START) {
            if (!$hospital_code) {
                $hospital_code = 0;
            }
            return $hospital_code;
        }

        $query = $this->db->select('id')->where("hospital_code", $hospital_code)->limit(1)->get("ml_hospital");
        if ($query) {
            $id = $query->row_array()["id"];
            if (!$id) {
                $id = 0;
            }
            return $id;
        }
        return 0;
    }

    /**
     * @return SphinxClient
     */
    private function get_instance_of_sphinx_client()
    {
        if (!self::$sc) {
            $this->load->library('sphinxclient');

            $cl = new SphinxClient ();

            $cl->SetServer ( CORESEEK_IP_HOSPITAL, CORESEEK_PORT_HOSPITAL );
            $cl->SetConnectTimeout ( 1 );
            $cl->SetArrayResult ( true );
            $cl->SetWeights ( array ( 100, 1 ) );

            self::$sc = $cl;
        }

        return self::$sc;
    }

    public function queryByName($q)
    {
        $cl = $this->get_instance_of_sphinx_client();

        $cl->SetLimits(0, 40);

        $cl->SetRankingMode ( SPH_RANK_PROXIMITY_BM25 );

        $cl->SetSortMode(SPH_SORT_EXTENDED, 'grade_num DESC, @weight DESC');

        $cl->SetMatchMode(SPH_MATCH_ALL);
        $res = $cl->Query($q, '*');

//        $cl->SetMatchMode(SPH_MATCH_EXTENDED); # 指定字段查询, SPH_MATCH_EXTENDED
//        $res = $cl->Query("@alias($q)", '*');

        $data = $res["matches"];

        $result = array();
        if (empty($data)) {
            return $result;
        }
        
        foreach ($data as $item) {
            if (empty($item["attrs"])) {
                continue;
            }

            $tmp = $item["attrs"];
            $tmp["hospital_id"] = $item["id"];
            $result[] = $tmp;
        }

        return $result;
    }
    //获取医院ID
    public function getHospitalId($hospital_name)
    {
        $query = $this->db->select('id')->where("hospital_name", trim($hospital_name))->limit(1)->get("ml_hospital");
        if ($query) {
            $id = $query->row_array()["id"];
            if (!$id) {
                $id = 0;
            }
            return $id;
        }
        return 0;
    }
}